/**
 * 门店和房间API服务
 * 
 * 用途：提供门店和房间数据的网络请求功能
 * 方法：使用OkHttp进行网络请求，Gson进行JSON解析
 * 原理：封装HTTP请求逻辑，提供异步回调接口
 */
package com.example.brain_wave.api.service

import com.example.brain_wave.api.model.*
import com.example.brain_wave.config.AppConfig
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.util.concurrent.TimeUnit
import android.content.Context

class StoreRoomApiService(private val context: Context) {
    
    private val appConfig = AppConfig.getInstance(context)
    private val client = OkHttpClient.Builder()
        .connectTimeout(appConfig.connectTimeout.toLong(), TimeUnit.SECONDS)
        .writeTimeout(appConfig.writeTimeout.toLong(), TimeUnit.SECONDS)
        .readTimeout(appConfig.readTimeout.toLong(), TimeUnit.SECONDS)
        .build()
    
    private val gson = Gson()
    
    // API配置 - 从配置文件读取
    private val baseUrl: String get() = appConfig.storeRoomApiBaseUrl
    private val token: String get() = appConfig.storeRoomApiToken
    private val server: String get() = appConfig.storeRoomApiServer
    
    /**
     * 获取所有门店数据
     */
    suspend fun getStores(limit: Int = 100, page: Int = 1): Result<List<StoreApiModel>> {
        return withContext(Dispatchers.IO) {
            try {
                val url = "$baseUrl/admin/store/apiStores?limit=$limit&page=$page"
                println("🌐 发送门店API请求: $url")
                println("📋 请求头: token=$token, server=$server")
                
                val request = Request.Builder()
                    .url(url)
                    .addHeader("token", token)
                    .addHeader("server", server)
                    .build()
                
                val response = client.newCall(request).execute()
                println("📡 响应状态: ${response.code} ${response.message}")
                
                if (response.isSuccessful) {
                    val responseBody = response.body?.string()
                    println("📄 响应内容长度: ${responseBody?.length ?: 0}")
                    println("📄 响应内容: ${responseBody?.take(500)}...")
                    
                    if (responseBody != null) {
                        try {
                            // 使用Gson的TypeToken来正确解析泛型类型
                            val type = object : com.google.gson.reflect.TypeToken<StoreApiResponse>() {}.type
                            val apiResponse: StoreApiResponse = gson.fromJson(responseBody, type)
                            println("✅ JSON解析成功: code=${apiResponse.code}, msg=${apiResponse.msg}")
                            println("📊 门店数量: ${apiResponse.data.list.size}")
                            
                            if (apiResponse.code == 1) {
                                apiResponse.data.list.forEach { store ->
                                    println("🏪 门店: ID=${store.id}, 名称=${store.name}, 省份=${store.province_id_text}")
                                }
                                Result.success(apiResponse.data.list)
                            } else {
                                println("❌ API返回错误: ${apiResponse.msg}")
                                Result.failure(Exception("API错误: ${apiResponse.msg}"))
                            }
                        } catch (e: Exception) {
                            println("❌ JSON解析失败: ${e.message}")
                            println("📄 原始响应内容: $responseBody")
                            Result.failure(Exception("JSON解析失败: ${e.message}"))
                        }
                    } else {
                        println("❌ 响应体为空")
                        Result.failure(Exception("响应体为空"))
                    }
                } else {
                    println("❌ HTTP请求失败: ${response.code} ${response.message}")
                    Result.failure(Exception("HTTP错误: ${response.code} ${response.message}"))
                }
            } catch (e: Exception) {
                println("❌ API调用异常: ${e.message}")
                e.printStackTrace()
                Result.failure(e)
            }
        }
    }
    
    /**
     * 获取指定门店的房间数据
     */
    suspend fun getRooms(storeId: Int, limit: Int = 5, page: Int = 1): Result<List<RoomApiModel>> {
        return withContext(Dispatchers.IO) {
            try {
                val url = "$baseUrl/admin/room/apiRooms?limit=$limit&page=$page&store_id=$storeId"
                println("🏠 发送房间API请求: $url")
                println("📋 请求头: token=$token, server=$server")
                println("🏪 查询门店ID: $storeId")
                
                val request = Request.Builder()
                    .url(url)
                    .addHeader("token", token)
                    .addHeader("server", server)
                    .build()
                
                val response = client.newCall(request).execute()
                println("📡 房间API响应状态: ${response.code} ${response.message}")
                
                if (response.isSuccessful) {
                    val responseBody = response.body?.string()
                    println("📄 房间响应内容长度: ${responseBody?.length ?: 0}")
                    println("📄 房间响应内容: ${responseBody?.take(500)}...")
                    
                    if (responseBody != null) {
                        try {
                            val type = object : TypeToken<RoomApiResponse>() {}.type
                            val apiResponse: RoomApiResponse = gson.fromJson(responseBody, type)
                            println("✅ 房间JSON解析成功: code=${apiResponse.code}, msg=${apiResponse.msg}")
                            println("📊 房间数量: ${apiResponse.data.list.size}")
                            
                            if (apiResponse.code == 1) {
                                apiResponse.data.list.forEach { room ->
                                    println("🏠 房间: ID=${room.id}, 名称=${room.name}, 门店ID=${room.store_id}")
                                }
                                Result.success(apiResponse.data.list)
                            } else {
                                println("❌ 房间API返回错误: ${apiResponse.msg}")
                                Result.failure(Exception("API错误: ${apiResponse.msg}"))
                            }
                        } catch (e: Exception) {
                            println("❌ 房间JSON解析失败: ${e.message}")
                            println("📄 房间原始响应内容: $responseBody")
                            e.printStackTrace()
                            Result.failure(Exception("JSON解析失败: ${e.message}"))
                        }
                    } else {
                        println("❌ 房间响应体为空")
                        Result.failure(Exception("响应体为空"))
                    }
                } else {
                    println("❌ 房间HTTP请求失败: ${response.code} ${response.message}")
                    Result.failure(Exception("HTTP错误: ${response.code} ${response.message}"))
                }
            } catch (e: Exception) {
                println("❌ 房间API调用异常: ${e.message}")
                e.printStackTrace()
                Result.failure(e)
            }
        }
    }
    
    /**
     * 设置API配置（可选，用于动态配置）
     */
    fun updateApiConfig(newBaseUrl: String? = null, newToken: String? = null) {
        // 这里可以实现动态配置更新逻辑
        // 由于当前使用的是不可变的配置，暂时保留接口
    }
}